#!/usr/bin/env python3
# -*- coding: utf-8 -*-

# Copyright 2014 Lukas Kemmer
#
# Licensed under the Apache License, Version 2.0 (the "License"); you
# may not use this file except in compliance with the License. You
# may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
# implied. See the License for the specific language governing
# permissions and limitations under the License.

import re
import os
import sys
from core import enumerate_files, get_root_dir

license_template = """# Copyright 20\d\d Lukas Kemmer
#
# Licensed under the Apache License, Version 2.0 \(the "License"\); you
# may not use this file except in compliance with the License\. You
# may obtain a copy of the License at
#
# http://www\.apache\.org/licenses/LICENSE-2\.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
# implied. See the License for the specific language governing
# permissions and limitations under the License\.

"""

cpp_encoding_preamble = "// -\*- coding: us-ascii-unix -\*-\n"

license_regex_cpp = re.compile(cpp_encoding_preamble + license_template.replace("#", "//"),
                               re.MULTILINE)

# Python-Shebang and encoding followed by a blank line
py_encoding_preamble = """(?:#!/usr/bin/env python3
# -\*- coding: utf-8 -\*-

)?"""
license_regex_py = re.compile(py_encoding_preamble + license_template, re.MULTILINE)

generated_file_prefix = "// Generated by"

def _find_cpp_license_preamble(filename):
    f = open(filename)
    text = f.read()
    if not license_regex_cpp.match(text) and not text.startswith(generated_file_prefix):
        print(filename)

def _find_py_license_preamble(filename):
    if os.path.basename(filename) == "__init__.py":
        return

    f = open(filename)
    text = f.read()

    if not license_regex_py.match(text):
        print(filename)

IGNORED_PATHS = ("installer", "test", "tablet", "example_py", "default_ini.py", "generated-methods.hh")

def ignored(filename):
    for p in IGNORED_PATHS:
        if filename.find(p) != -1:
            return True
    return False

if __name__ == '__main__':
    root_dir = get_root_dir()
    cpp_files = enumerate_files(root_dir, (".hh", ".cpp"))
    for filename in cpp_files:
        if not ignored(filename):
            _find_cpp_license_preamble(filename)

    py_files = enumerate_files(root_dir, (".py",))
    for filename in py_files:
        if not ignored(filename):
            _find_py_license_preamble(filename)
